package org.sluggard.tangela.tencent;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import com.mime.qweibo.OauthKey;
import com.mime.qweibo.QParameter;
import com.mime.qweibo.QWeiboRequest;
import com.mime.qweibo.examples.QWeiboType.ResultType;

public class OAuth {
	
	private static final String customKey = "9dc8fe98e75f4a448292b138b67f8729";
	
	private static final String customSecret = "09180e91846af4d44571cc4d3766785a";

	private static String tokenKey = null;
	private static String tokenSecrect = null;
	
//	private static String verify = null;
	
	private static int state = 0;
	
	public static boolean isOk() {
		return state == 2;
	}

	public static void setState(int state) {
		OAuth.state = state;
	}

	public static int getState() {
		return state;
	}

	/**
	 * Get request token.
	 * 
	 * @param customKey
	 *            Your AppKey.
	 * @param customSecret
	 *            Your AppSecret.
	 * @return The request token.
	 */
	public static String getRequestToken() {
		String url = "https://open.t.qq.com/cgi-bin/request_token";
		List<QParameter> parameters = new ArrayList<QParameter>();
		OauthKey oauthKey = new OauthKey();
		oauthKey.customKey = customKey;
		oauthKey.customSecrect = customSecret;
		//The OAuth Call back URL(You should encode this url if it
		//contains some unreserved characters).
		oauthKey.callbackUrl = "null";

		QWeiboRequest request = new QWeiboRequest();
		String res = null;
		try {
			res = request.syncRequest(url, "GET", oauthKey, parameters, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public static void askPin(){
		if( !java.awt.Desktop.isDesktopSupported() ) {

            System.err.println( "Desktop is not supported (fatal)" );
            System.exit( 1 );
        }
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
        if(desktop == null || !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {

            System.err.println( "Desktop doesn't support the browse action (fatal)" );
            System.exit( 1 );
        }
        try {
			desktop.browse(new URI("http://open.t.qq.com/cgi-bin/authorize?oauth_token=" + OAuth.tokenKey));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit( 1 );
		} catch (URISyntaxException e) {
			e.printStackTrace();
			System.exit( 1 );
		}
	}
	
	/**
	 * Get access token.
	 * 
	 * @param customKey
	 *            Your AppKey.
	 * @param customSecret
	 *            Your AppSecret
	 * @param requestToken
	 *            The request token.
	 * @param requestTokenSecret
	 *            The request token Secret
	 * @param verify
	 *            The verification code.
	 * @return
	 */
	public static String getAccessToken(String verify) {

		String url = "https://open.t.qq.com/cgi-bin/access_token";
		List<QParameter> parameters = new ArrayList<QParameter>();
		OauthKey oauthKey = new OauthKey();
		oauthKey.customKey = customKey;
		oauthKey.customSecrect = customSecret;
		oauthKey.tokenKey = tokenKey;
		oauthKey.tokenSecrect = tokenSecrect;
		oauthKey.verify = verify;
//		OAuth.verify = verify;

		QWeiboRequest request = new QWeiboRequest();
		String res = null;
		try {
			res = request.syncRequest(url, "GET", oauthKey, parameters, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	/**
	 * Publish a Weibo message.
	 * 
	 * @param customKey
	 *            Your AppKey
	 * @param customSecret
	 *            Your AppSecret
	 * @param requestToken
	 *            The access token
	 * @param requestTokenSecrect
	 *            The access token secret
	 * @param content
	 *            The content of your message
	 * @param pic
	 *            The files of your images.
	 * @param format
	 *            Response format, xml or json(Default).
	 * @return Result info based on the specified format.
	 */
	public static String publishMsg(TencentToken token, String content,
			String pic, ResultType format) {

		List<QParameter> files = new ArrayList<QParameter>();
		String url = null;
		String httpMethod = "POST";

		if (pic == null || pic.trim().equals("")) {
			url = "http://open.t.qq.com/api/t/add";
		} else {
			url = "http://open.t.qq.com/api/t/add_pic";
			files.add(new QParameter("pic", pic));
		}

		OauthKey oauthKey = new OauthKey();
		oauthKey.customKey = customKey;
		oauthKey.customSecrect = customSecret;
		oauthKey.tokenKey = token.getAccessKey();
		oauthKey.tokenSecrect = token.getAccessSecrect();

		List<QParameter> parameters = new ArrayList<QParameter>();

		String strFormat = null;
		if (format == ResultType.ResultType_Xml) {
			strFormat = "xml";
		} else if (format == ResultType.ResultType_Json) {
			strFormat = "json";
		} else {
			return "";
		}

		parameters.add(new QParameter("format", strFormat));
		parameters.add(new QParameter("content", content));
		parameters.add(new QParameter("clientip", "127.0.0.1"));

		QWeiboRequest request = new QWeiboRequest();
		String res = null;
		try {
			res = request.syncRequest(url, httpMethod, oauthKey, parameters,
					files);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	static boolean parseToken(String response) {
		
		System.out.println(response);
		if (response == null || response.equals("")) {
			return false;
		}
	
		String[] tokenArray = response.split("&");
	
		if (tokenArray.length < 2) {
			return false;
		}
	
		String strTokenKey = tokenArray[0];
		String strTokenSecrect = tokenArray[1];
	
		String[] token1 = strTokenKey.split("=");
		if (token1.length < 2) {
			return false;
		}
		tokenKey = token1[1];
	
		String[] token2 = strTokenSecrect.split("=");
		if (token2.length < 2) {
			return false;
		}
		tokenSecrect = token2[1];
	
		return true;
	}
	
	static boolean parseToken(String response, TencentToken token) {
		
		System.out.println(response);
		if (response == null || response.equals("")) {
			return false;
		}
	
		String[] tokenArray = response.split("&");
	
		if (tokenArray.length < 2) {
			return false;
		}
	
		String strTokenKey = tokenArray[0];
		String strTokenSecrect = tokenArray[1];
	
		String[] token1 = strTokenKey.split("=");
		if (token1.length < 2) {
			return false;
		}
		token.setAccessKey(token1[1]);
	
		String[] token2 = strTokenSecrect.split("=");
		if (token2.length < 2) {
			return false;
		}
		token.setAccessSecrect(token2[1]);
	
		return true;
	}
}
